package com.funsport.controller.mobile;

import com.funsport.common.Result;
import com.funsport.dto.request.UpdateUserRequest;
import com.funsport.dto.response.UserInfoResponse;
import com.funsport.entity.User;
import com.funsport.security.SecurityUtils;
import com.funsport.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 移动端用户Controller
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Tag(name = "移动端用户", description = "移动端用户信息相关接口")
@RestController
@RequestMapping("/mobile/user")
@RequiredArgsConstructor
public class MobileUserController {

    private final IUserService userService;

    @Value("${file.upload.path:/tmp/fun-sport-uploads}")
    private String uploadPath;

    @Value("${file.upload.url:http://localhost:8858/uploads}")
    private String uploadUrl;

    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取当前用户信息")
    @GetMapping("/info")
    public Result<UserInfoResponse> getUserInfo() {
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
        
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 手动设置所有字段，确保数据完整
        UserInfoResponse response = new UserInfoResponse();
        response.setId(user.getId());
        response.setNickname(user.getNickname());
        response.setAvatar(user.getAvatar());
        response.setGender(user.getGender());
        response.setPhone(user.getPhone());
        response.setEmail(user.getEmail());
        response.setCity(user.getCity());
        response.setDistrict(user.getDistrict());
        response.setBio(user.getBio());
        response.setSportsPreferences(user.getSportsPreferences());
        response.setSkillLevel(user.getSkillLevel());
        response.setRole(user.getRole() != null ? user.getRole().getValue() : null);
        response.setStatus(user.getStatus() != null ? user.getStatus().getValue() : null);
        response.setPoints(user.getPoints());
        response.setLevel(user.getLevel());
        response.setCreatedAt(user.getCreatedAt());
        response.setUpdatedAt(user.getUpdatedAt());

        log.info("获取用户信息: userId={}, nickname={}, city={}", userId, response.getNickname(), response.getCity());

        return Result.success(response);
    }

    /**
     * 更新当前用户信息
     */
    @Operation(summary = "更新当前用户信息")
    @PutMapping("/info")
    public Result<UserInfoResponse> updateUserInfo(@Valid @RequestBody UpdateUserRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
        
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        if (request.getNickname() != null) {
            user.setNickname(request.getNickname());
        }
        if (request.getAvatar() != null) {
            user.setAvatar(request.getAvatar());
        }
        if (request.getGender() != null) {
            user.setGender(request.getGender());
        }
        if (request.getPhone() != null) {
            user.setPhone(request.getPhone());
        }
        // 邮箱处理：如果为空字符串则设置为null，避免唯一索引冲突
        if (request.getEmail() != null) {
            String email = request.getEmail().trim();
            user.setEmail(email.isEmpty() ? null : email);
        }
        if (request.getCity() != null) {
            user.setCity(request.getCity());
        }
        if (request.getDistrict() != null) {
            user.setDistrict(request.getDistrict());
        }
        if (request.getBio() != null) {
            user.setBio(request.getBio());
        }
        if (request.getSportsPreferences() != null) {
            user.setSportsPreferences(request.getSportsPreferences());
        }
        if (request.getSkillLevel() != null) {
            user.setSkillLevel(request.getSkillLevel());
        }

        userService.updateById(user);
        log.info("用户信息更新成功: userId={}", userId);

        // 返回更新后的完整用户信息
        UserInfoResponse response = new UserInfoResponse();
        response.setId(user.getId());
        response.setNickname(user.getNickname());
        response.setAvatar(user.getAvatar());
        response.setGender(user.getGender());
        response.setPhone(user.getPhone());
        response.setEmail(user.getEmail());
        response.setCity(user.getCity());
        response.setDistrict(user.getDistrict());
        response.setBio(user.getBio());
        response.setSportsPreferences(user.getSportsPreferences());
        response.setSkillLevel(user.getSkillLevel());
        response.setRole(user.getRole() != null ? user.getRole().getValue() : null);
        response.setPoints(user.getPoints());
        response.setLevel(user.getLevel());
        response.setCreatedAt(user.getCreatedAt());
        response.setUpdatedAt(user.getUpdatedAt());

        log.info("返回更新后的用户信息: nickname={}", response.getNickname());

        return Result.success(response);
    }

    /**
     * 获取用户积分信息
     */
    @Operation(summary = "获取用户积分信息")
    @GetMapping("/points")
    public Result<Object> getUserPoints() {
        Long userId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(userId);
        
        if (user == null) {
            return Result.error("用户不存在");
        }

        // 返回积分信息
        return Result.success(new Object() {
            public final Integer points = user.getPoints();
            public final Integer level = user.getLevel();
        });
    }

    /**
     * 上传头像
     */
    @Operation(summary = "上传头像")
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }

        try {
            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持上传图片文件");
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString() + extension;
            
            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 保存文件
            Path filePath = Paths.get(uploadPath, fileName);
            Files.write(filePath, file.getBytes());

            // 构建访问URL
            String fileUrl = uploadUrl + "/" + fileName;

            // 返回文件URL
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);

            log.info("头像上传成功: {}", fileUrl);
            return Result.success(result);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            return Result.error("文件上传失败");
        }
    }
}

